package upload;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author DCSGO
 * @version 1.0
 * 1.编写一个服务端,和一个客户端
 * 2.服务器端在9999端口监听
 * 3.客户端连接到服务端，发送一张图片shoes.jpg
 * 4.服务器端接收到客户端发送的图片，保存到 src/upload/shoes.copy.jpg 下,发送“收到图片”再退出
 * 5.客户端接收到服务端发送的“收到图片"，再退出
 * 6.该程序要求使用 StreamUtils.java
 */
public class TCPFileUploadServer {
    public static void main(String[] args) throws Exception {
        int port = 9999;
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("正在监听 " + port + " 端口...");
        Socket socket = serverSocket.accept();
        System.out.println("有主机连接到 " + port + " 端口！");
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        byte[] bytes = StreamUtils.streamToByteArray(bis);
        System.out.println(socket.getInetAddress().getHostName() + "发送的图片已接收！");
        String destFilePath = "src\\upload\\shoes.copy.jpg";

        System.out.println("正在写入到本地...");
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
        bos.write(bytes);
        System.out.println("写入本地完成！");

        BufferedWriter bos2 = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bos2.write("收到图片");
        bos2.newLine();
        bos2.flush();
        socket.shutdownOutput();
        System.out.println("回传信息已发送！");

        //关闭相关资源
        bos2.close();
        bos.close();
        bis.close();
        socket.close();
        serverSocket.close();
    }
    /*
     * 正在监听 9999 端口...
     * 有主机连接到 9999 端口！
     * DCSGO发送的图片已接收！
     * 正在写入到本地...
     * 写入本地完成！
     * 回传信息已发送！
     *
     * 进程已结束，退出代码为 0
     */
}
